package com.sinoglobal.sinostore.fragment;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.ShareAbstractActivity;
import com.sinoglobal.sinostore.SinoStore;
import com.sinoglobal.sinostore.activity.BusinessAddressActivity;
import com.sinoglobal.sinostore.activity.ConsultListActivity;
import com.sinoglobal.sinostore.activity.EvaluationListActivity;
import com.sinoglobal.sinostore.activity.GoodsDetailActivity;
import com.sinoglobal.sinostore.activity.TurntableImageActivity;
import com.sinoglobal.sinostore.adapter.GoodsBannerPagerAdapter;
import com.sinoglobal.sinostore.adapter.MyViewPagerAdapter;
import com.sinoglobal.sinostore.adapter.ViewHolder;
import com.sinoglobal.sinostore.bean.CommentListVo;
import com.sinoglobal.sinostore.bean.CommentVo;
import com.sinoglobal.sinostore.bean.GoodsDetailsVo;
import com.sinoglobal.sinostore.bean.ImageVo;
import com.sinoglobal.sinostore.system.Constants;
import com.sinoglobal.sinostore.utils.ApiDebugUtil;
import com.sinoglobal.sinostore.utils.TextUtil;
import com.sinoglobal.sinostore.widget.HackyViewPager;
import com.sinoglobal.sinostore.widget.MyScrollView;
import com.yahoo.mobile.client.android.util.PixelUtil;
/**
 * 
* @title: GoodsDetailFragment.java 
* @package com.chiliring.sinostore.fragment 
* @description: TODO(商品详情) 
* @author LK
* @date 2015-1-20 下午8:44:36
 */
public final class GoodsDetailFragment extends Fragment implements OnClickListener,OnCheckedChangeListener{
	public static GoodsDetailFragment newInstance() {
		GoodsDetailFragment fragment = new GoodsDetailFragment();
		return fragment;
	}
	
	/**支持自取**/
	private static final String ISINVITE = "1";
	
	MyScrollView myScrollView;
	
	HackyViewPager viewPager;

	View sliderView;

	RadioGroup rgPic;
	
	/**商品名称**/
	private TextView tvGoodsName;
	/**商品价格**/
	private TextView tvGoodsPrice;
	/**销量**/
	private TextView tvSales;
	/**倒计时**/
	private LinearLayout llCountdown;
	/**计时**/
	private TextView tvSecondKill;
	/**库存**/
	private TextView tvInventory;
	/**限购**/
	private TextView tvPurchasing;
	/**自取**/
	private TextView tvInvite;
	/**虚拟商品**/
	private TextView tvVirtualGoods;
	/**评价和咨询**/
	private HackyViewPager vpCommentAndConsult;
	/**商品评价和咨询**/
	private RadioGroup rgGoodsPicDesc;
	/**商品评价**/
	private RadioButton rbGoodsComment;
	/**商品咨询**/
	private RadioButton rbGoodsConsult;
	/**商家地址**/
	private LinearLayout llBusinessAddress;
	/**查看商家地址**/
	private TextView tvLookAddress;
	/**商家地址**/
	private TextView tvAddress;
	/**商家电话**/
	private TextView tvPhone;
	/**拨打商家电话**/
	private ImageView ivCallPhone;
	/**商品原价**/
	private TextView tvGoodsOriginalPrice;
	/**分享**/
	private ImageView btnShare;
	
	/**将从fragment中获取的订单数据push到activity中**/
	private OrderDataInterface orderDataInterface;
	
	/**商品Id**/
	private String goodsId;
	
	private String activityId;
	
	
	private List<View> viewList = new ArrayList<View>();
	
	private MyViewPagerAdapter adapter;
	
	private View goodsDetailView;
	
	/**记录商家电话**/
	private String shopTel;
	
	private GoodsDetailsVo detailsVo;
	
	private Handler mHandler;
	
	private Runnable runnable;
	
	private int timing;
	
	/**是否加载过数据**/
	private boolean loading = true;
	
	private ReceiveBroadCast receiveBroadCast;
	
	/**倒计时时间**/
	private long customTime;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		goodsId = getActivity().getIntent().getStringExtra("goodsId");
		activityId = getActivity().getIntent().getStringExtra("activityId");
		if(TextUtils.isEmpty(activityId)){
			activityId = "";
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		goodsDetailView=inflater.inflate(R.layout.shop_fragment_goods_detail, null);
		goodsDetailView.setVisibility(View.INVISIBLE);
		initView(goodsDetailView);
		return goodsDetailView;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(loading){
			loadData();
			loading = false;
		}
	}
	
	@Override
	public void onAttach(Activity activity) {
		if(activity instanceof OrderDataInterface){
			orderDataInterface = (OrderDataInterface)activity;
		}
		receiveBroadCast = new ReceiveBroadCast();
		IntentFilter filter = new IntentFilter();  
	    filter.addAction("com.gasFragment");    //只有持有相同的action的接受者才能接收此广播  
	    activity.registerReceiver(receiveBroadCast, filter); 
	    super.onAttach(activity);
	}
	
	/**使用广播结束数据是否需要更新UI**/
	private class ReceiveBroadCast extends BroadcastReceiver  
    {  
        @Override  
        public void onReceive(Context context, Intent intent){
           loading = intent.getBooleanExtra("reloading", false);
        }  
    } 
	
	
	/**
	 * 
	* @author LK
	* @methods loadData 
	* @description 描述信息 加载数据
	* @date 2015-1-15 下午8:51:57 参数说明
	 */
	private void loadData() {
		if(isAdded()){
			final ProgressDialog progressDialog=new ProgressDialog(getActivity());
			RequestParams params = new RequestParams();
			if(TextUtils.isEmpty(activityId)){
				params.addQueryStringParameter("por", "102");
			}else{
				params.addQueryStringParameter("por", "603");
				params.addQueryStringParameter("h_id",activityId);
			}
			params.addQueryStringParameter("proIden", Constants.STOREFLAG);
			params.addQueryStringParameter("id", goodsId);
			if(!TextUtils.isEmpty(Constants.userCenterId)){
				params.addQueryStringParameter("user_id", Constants.userCenterId);
			}
			HttpUtils http = new HttpUtils();
			http.send(HttpMethod.POST,Constants.STORE_URL,params,new RequestCallBack<String>() {
				@Override
				public void onStart() {
					LogUtils.i("Result=="+this.getRequestUrl());
					try {
						progressDialog.show();
					} catch (Exception e) {
					}
				}
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						progressDialog.dismiss();
					} catch (Exception e) {
					}
					String result = responseInfo.result;
					LogUtils.e("Result====="+result);
					if(!TextUtils.isEmpty(result)){
						try {
							GoodsDetailsVo entity = JSON.parseObject(result, GoodsDetailsVo.class);
							if(null != entity){
								if(Constants.STORE_SUCCESS_CODE.equals(entity.getCode())){
									Constants.PIC_HOST = entity.getHost();
									if(null != entity.images){
										initViewPage(entity.images);
									}
									setData(entity);
									detailsVo = entity;
									//加载评论数据
									loadComment();
									orderDataInterface.setOrderData(entity);
								}else if(Constants.STORE_GOODSSOLDOUT_CODE.equals(entity.getCode())){
									orderDataInterface.setOrderData(entity);
								}
							}
						} catch (Exception e) {
						}
					}
				}
	
				@Override
				public void onFailure(HttpException error, String msg) {
					try {
						progressDialog.dismiss();
					} catch (Exception e) {
					}
				}
			});
		}
	}
	protected <T extends View>  T getViewById(View view, int id) {
		return (T) view.findViewById(id);
	}
	private void initView(View view){
		myScrollView=getViewById(view, R.id.goodsScrollView);
		
		viewPager=getViewById(view, R.id.banner_viewpager);

		sliderView=getViewById(view, R.id.slider);
		rgPic=getViewById(view, R.id.rgPic);
		
		tvGoodsName = (TextView)view.findViewById(R.id.tv_goods_name);
		tvGoodsPrice = (TextView)view.findViewById(R.id.tv_goods_price);
		tvSales = (TextView)view.findViewById(R.id.tv_sales);
		llCountdown = (LinearLayout)view.findViewById(R.id.ll_countdown);
		tvSecondKill = (TextView)view.findViewById(R.id.tv_seconds_kill);
		tvInventory = (TextView)view.findViewById(R.id.tv_inventory);
		tvPurchasing = (TextView)view.findViewById(R.id.tv_purchasing);
		tvInvite = (TextView)view.findViewById(R.id.tv_invite);
		tvVirtualGoods = (TextView)view.findViewById(R.id.tv_virtual_goods);
		vpCommentAndConsult = (HackyViewPager)view.findViewById(R.id.viewpager);
		rgGoodsPicDesc = (RadioGroup)view.findViewById(R.id.rgGoodsPicDesc);
		rbGoodsComment = (RadioButton)view.findViewById(R.id.rbGoodsDesc);
		rbGoodsConsult = (RadioButton)view.findViewById(R.id.rbVenderDesc);
		llBusinessAddress = (LinearLayout)view.findViewById(R.id.ll_business_address);
		tvLookAddress = (TextView)view.findViewById(R.id.tv_look_address);
		tvAddress = (TextView)view.findViewById(R.id.tv_address);
		tvPhone = (TextView)view.findViewById(R.id.tv_phone);
		ivCallPhone = (ImageView)view.findViewById(R.id.iv_call_phone);
		tvGoodsOriginalPrice = (TextView)view.findViewById(R.id.tv_goods_original_price);
		btnShare = (ImageView)view.findViewById(R.id.btn_share);
		
		rgGoodsPicDesc.setOnCheckedChangeListener(this);
		tvLookAddress.setOnClickListener(this);
		ivCallPhone.setOnClickListener(this);
		btnShare.setOnClickListener(this);
		viewPager.getLayoutParams().height=SinoStore.WIDTHPIXELS;
		vpCommentAndConsult.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					rbGoodsComment.setChecked(true);
					break;
				case 1:
					rbGoodsConsult.setChecked(true);
					break;
				default:
					break;
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}
		});
		adapter = new MyViewPagerAdapter(viewList);
		vpCommentAndConsult.setAdapter(adapter);
	}
	
	/**
	 * 
	 * @author LK
	 * @methods setData 
	 * @description 描述信息 填充页面数据
	 * @date 2015-1-19 下午7:11:54 参数说明
	 */
	private void setData(GoodsDetailsVo entity){
		goodsDetailView.setVisibility(View.VISIBLE);
		tvGoodsName.setText(entity.name);
		//是否参与活动
		if(Constants.SECONDKILL_ACTIVITY.equals(entity.activity_type)){
			llCountdown.setVisibility(View.VISIBLE);
			tvSales.setVisibility(View.GONE);
			tvGoodsPrice.setText(String.format("秒杀价%s元", entity.ms_price));
			tvGoodsOriginalPrice.setVisibility(View.VISIBLE);
			tvGoodsOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
			if(TextUtil.isZeroOrNull(entity.price) && !TextUtil.isZeroOrNull(entity.cash)){//积分单价为零，现金不为零，为现金支付
				tvGoodsOriginalPrice.setText(String.format("原价%s元", entity.cash));
			}else if(TextUtil.isZeroOrNull(entity.cash) && !TextUtil.isZeroOrNull(entity.price)){//现金单价为零，为积分支付
				tvGoodsOriginalPrice.setText(String.format("原价%s%s", entity.price,getString(R.string.score_unit)));
			}else{//两个都不为零则为现金加积分支付
				tvGoodsOriginalPrice.setText(String.format("原价%s元+%s%s", entity.cash,entity.price,getString(R.string.score_unit)));
			}
			customTime = Long.parseLong(entity.end_time);
			customClock();
		}else{
			llCountdown.setVisibility(View.GONE);
			tvSales.setVisibility(View.VISIBLE);
			tvGoodsOriginalPrice.setVisibility(View.GONE);
			if(TextUtil.isZeroOrNull(entity.price) && !TextUtil.isZeroOrNull(entity.cash)){//积分单价为零，现金不为零，为现金支付
				tvGoodsPrice.setText(String.format("%s元", entity.cash));
			}else if(TextUtil.isZeroOrNull(entity.cash) && !TextUtil.isZeroOrNull(entity.price)){//现金单价为零，为积分支付
				tvGoodsPrice.setText(String.format("%s%s", entity.price,getString(R.string.score_unit)));
			}else{//两个都不为零则为现金加积分支付
				tvGoodsPrice.setText(String.format("%s元+%s%s", entity.cash,entity.price,getString(R.string.score_unit)));
			}
		}
		tvSales.setText(String.format("销量%s件", entity.bum_convert));
		tvInventory.setText(String.format("库存%s件", entity.nums));
		if("0".equals(entity.restriction)){
			tvPurchasing.setVisibility(View.INVISIBLE);
		}else{
			tvPurchasing.setText(String.format("限购%s件", entity.restriction));
		}
		if(Constants.VIRTUALGOODS.equals(entity.type)){
			llBusinessAddress.setVisibility(View.VISIBLE);
			tvVirtualGoods.setText(String.format("使用有效期：%s至%s", entity.use_start_time,entity.use_end_time));
			tvAddress.setText(String.format("商家地址：%s", entity.shop_addr));
			tvPhone.setText(String.format("电话：%s", entity.shop_phone));
			shopTel = entity.shop_phone;
			tvInvite.setVisibility(View.INVISIBLE);
		}else{
			llBusinessAddress.setVisibility(View.GONE);
			tvVirtualGoods.setVisibility(View.GONE);
			//支持自取
			if(ISINVITE.equals(entity.is_self)){
				tvInvite.setVisibility(View.VISIBLE);
			}else{
				tvInvite.setVisibility(View.INVISIBLE);
			}
		}
	}
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		int checkedRadioButtonId = group.getCheckedRadioButtonId();
		if (checkedRadioButtonId == R.id.rbGoodsDesc) {
			vpCommentAndConsult.setCurrentItem(0);
		} else if (checkedRadioButtonId == R.id.rbVenderDesc) {
			vpCommentAndConsult.setCurrentItem(1);
		} else {
		}
	}
	
	/**
	 * 
	* @author LK
	* @methods initComment 
	* @description 描述信息 评价数据
	* @date 2015-1-20 下午2:13:36 参数说明
	 */
	private void initComment(CommentListVo commentList){
		if(isAdded()){
			View view = LayoutInflater.from(getActivity()).inflate(R.layout.shop_layout_comment_detail,null);
			LinearLayout commentView = ViewHolder.getViewById(view, R.id.comment_layout);
			LinearLayout noComment = ViewHolder.getViewById(view, R.id.no_comment);
			TextView tvLoadMoreComment = ViewHolder.getViewById(view, R.id.tv_loadmore_comment);
			tvLoadMoreComment.setOnClickListener(this);
			if(null != commentList.getJson() && commentList.getJson().size() > 0){
				tvLoadMoreComment.setOnClickListener(this);
				noComment.setVisibility(View.GONE);
				commentView.setVisibility(View.VISIBLE);
				TextView commentName = ViewHolder.getViewById(view, R.id.comment_name);
				commentName.setSingleLine(true);
				commentName.setEllipsize(TruncateAt.END);
				TextView commentTime = ViewHolder.getViewById(view, R.id.comment_time);
				TextView commentMessage = ViewHolder.getViewById(view, R.id.comment_message);
				commentMessage.setMaxLines(2);
				commentMessage.setEllipsize(TruncateAt.END);
				CommentVo commentVo = commentList.getJson().get(0);
				commentName.setText(commentVo.getNike_name());
				commentTime.setText(commentVo.getCreate_time());
				tvLoadMoreComment.setText(String.format("查看更多评价（%s）", commentList.getPageTotal()));
				try {
					commentMessage.setText(URLDecoder.decode(commentVo.getMessage(), "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}else{
				noComment.setVisibility(View.VISIBLE);
				commentView.setVisibility(View.GONE);
			}
			adapter.addView(view);
		}
	}
	
	/**
	 * 
	* @author LK
	* @methods initConsult 
	* @description 描述信息 初始化评论
	* @date 2015-1-20 下午2:25:40 参数说明
	 */
	private void initConsult(CommentListVo commentList){
		if(isAdded()){
			View view = LayoutInflater.from(getActivity()).inflate(R.layout.shop_layout_consult, null);
			LinearLayout consultView = ViewHolder.getViewById(view, R.id.layout_consult);
			LinearLayout noConsult = ViewHolder.getViewById(view, R.id.no_consult);
			TextView tvLoadMoreConsult = ViewHolder.getViewById(view, R.id.tv_loadmore_consult);
			tvLoadMoreConsult.setOnClickListener(this);
			if(null != commentList && commentList.getJson().size() > 0){
				noConsult.setVisibility(View.GONE);
				consultView.setVisibility(View.VISIBLE);
				//咨询时间
				TextView time = ViewHolder.getViewById(view, R.id.time);
				//发表咨询人
				TextView person = ViewHolder.getViewById(view, R.id.person_name);
				person.setSingleLine(true);
				person.setEllipsize(TruncateAt.END);
				//咨询为题
				TextView question = ViewHolder.getViewById(view, R.id.question);
				//回答
				TextView answer = ViewHolder.getViewById(view, R.id.answer);
				question.setMaxLines(1);
				question.setEllipsize(TruncateAt.END);
				answer.setMaxLines(1);
				answer.setEllipsize(TruncateAt.END);
				CommentVo entity = commentList.getJson().get(0);
				time.setText(entity.getCreate_time());
				person.setText(entity.getNike_name());
				question.setText(entity.getMessage());
				answer.setText(entity.getReply());
				tvLoadMoreConsult.setText(String.format("查看更多咨询（%s）", commentList.getPageTotal()));
			}else{
				noConsult.setVisibility(View.VISIBLE);
				consultView.setVisibility(View.GONE);
			}
			adapter.addView(view);
		}
	}
	/**
	 * 
	 * @author zrh
	 * @methods changeFragment 
	 * @description 切换到图文详情页面
	 * @date 2015年1月13日 下午4:48:13 参数说明
	 */
	private void changeFragment() {
		GoodsDetailActivity goodsDetailActivity=(GoodsDetailActivity) getActivity();
		goodsDetailActivity.toGoodsWebView();
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		int id = v.getId();
		if (id == R.id.tv_loadmore_comment) {
			intent = new Intent(getActivity(),EvaluationListActivity.class);
			intent.putExtra("goodsId", goodsId);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		} else if (id == R.id.tv_loadmore_consult) {
			intent = new Intent(getActivity(),ConsultListActivity.class);
			intent.putExtra("goodsId", goodsId);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		} else if (id == R.id.tv_look_address) {
			intent = new Intent(getActivity(),BusinessAddressActivity.class);
			intent.putExtra("pId", detailsVo.p_id);
			intent.putExtra("shopId", detailsVo.shop_id);
			intent.putExtra("goodsId", detailsVo.id);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		} else if (id == R.id.iv_call_phone) {
			intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+shopTel));
			startActivity(intent);
		} else if (id == R.id.btn_share) {
			String shareUrl = getString(R.string.shareUrl);
			String appName = getResources().getString(R.string.app_name);
			String text = appName+"商城里的"+detailsVo.name+",真心不错啊!快来看看吧!"+shareUrl;
			((ShareAbstractActivity)getActivity()).setShare(text, getString(R.string.shareTitle), null, shareUrl, 0, Constants.PIC_HOST+detailsVo.img_url);
		} else {
		}
	}
	
	public interface OrderDataInterface{
		public void setOrderData(GoodsDetailsVo detailsVo);
	}
	
	/**
	 * 
	* @author LK
	* @methods loadComment 
	* @description 描述信息  加载评论数据
	* @date 2015-1-20 下午2:35:00 参数说明
	 */
	private void loadComment(){
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("por", "104");
		params.addQueryStringParameter("proIden", Constants.STOREFLAG);
		params.addQueryStringParameter("limit1", "0");
		params.addQueryStringParameter("limit2", "1");
		params.addQueryStringParameter("id", goodsId);
		params.addQueryStringParameter("type", Constants.COMMENT_CODE);
		ApiDebugUtil.debug(params);
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.POST, Constants.STORE_URL,params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				if (!TextUtils.isEmpty(result)) {
					CommentListVo entity = JSON.parseObject(result, CommentListVo.class);
					if (Constants.STORE_SUCCESS_CODE.equals(entity.getCode())) {
						initComment(entity);
						//加载咨询数据
						loadConsult();
					}
				}
			}
		});
	}
	
	/**
	 * 
	* @author LK
	* @methods loadComment 
	* @description 描述信息  加载咨询数据
	* @date 2015-1-20 下午2:35:00 参数说明
	 */
	private void loadConsult(){
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("por", "104");
		params.addQueryStringParameter("proIden", Constants.STOREFLAG);
		params.addQueryStringParameter("limit1", "0");
		params.addQueryStringParameter("limit2", "1");
		params.addQueryStringParameter("id", goodsId);
		params.addQueryStringParameter("type", Constants.CONSULT_CODE);
		ApiDebugUtil.debug(params);
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.POST, Constants.STORE_URL,params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
			}
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				if (!TextUtils.isEmpty(result)) {
					CommentListVo entity;
					try {
						entity = JSON.parseObject(result, CommentListVo.class);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
				        Toast.makeText(getActivity(), "数据解析出错", 0).show();
						return;
					}
					if (Constants.STORE_SUCCESS_CODE.equals(entity.getCode())) {
						initConsult(entity);
					}
				}
			}
		});
	}
	
	/**
	 * 
	* @author LK
	* @methods initViewPage 
	* @description 描述信息  初始化轮播图
	* @date 2015-1-19 下午7:05:37
	* @param arrayList 参数说明
	 */
	private void initViewPage(ArrayList<ImageVo> imgs){
		rgPic.removeAllViews();
		for (int i =0;i<imgs.size();i++) {
			RadioButton radioButton=(RadioButton) LayoutInflater.from(getActivity()).inflate(R.layout.shop_radiobutton, null);
			rgPic.addView(radioButton);
		}
		RadioButton radioButton=(RadioButton) rgPic.getChildAt(0);
		radioButton.setChecked(true);
		final GoodsBannerPagerAdapter bannerPagerAdapter=new GoodsBannerPagerAdapter(getActivity(),imgs);
		viewPager.setAdapter(bannerPagerAdapter);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				RadioButton radioButton=(RadioButton) rgPic.getChildAt(position);
				radioButton.setChecked(true);
				sliderView.setVisibility(View.GONE);
				viewPager.setLocked(false);
				setTouchEventOnImg(bannerPagerAdapter, position);
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		if (bannerPagerAdapter.getCount()==1) {
			setTouchEventOnImg(bannerPagerAdapter, 0);
		}
	}
	
	private void setTouchEventOnImg(final GoodsBannerPagerAdapter bannerPagerAdapter,final int position) {
		if ( position==bannerPagerAdapter.getViews().size()-1) {
			final View iv=bannerPagerAdapter.getViews().get(position);
			viewPager.setLocked(true);
			iv.setLongClickable(true);//不设此项经常不能监听到touchUP事件
			iv.setOnTouchListener(new OnTouchListener() {
				int tempX;
				boolean isNext=false;
				boolean isClick=false;
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						tempX=(int) event.getX();
						break;
					case MotionEvent.ACTION_MOVE:
						int moveX = (int) event.getX();
						int deltaX=tempX-moveX;
						LogUtils.d("deltalX=="+deltaX);
						tempX=moveX;
						if(Math.abs(deltaX)<PixelUtil.dpToPx(getActivity(), 10)){//触发点击事件 查看大图
							isClick=true;
						}
						else if (deltaX>PixelUtil.dpToPx(getActivity(), 10)) {
							LogUtils.d("move isNext=true");
							isNext=true;
						}else{
							viewPager.setLocked(false);
						}
						break;
					case MotionEvent.ACTION_UP:
						if(isClick){
							Intent intent = new Intent(getActivity(), TurntableImageActivity.class);
							intent.putExtra("imgurls", bannerPagerAdapter.getData());
							intent.putExtra("index", position);
							intent.putExtra("type", 1);
							startActivity(intent);
							isClick=false;
							break;
						}
					case MotionEvent.ACTION_CANCEL://快速滑动超过view的位置
					default:
						LogUtils.d("event.event.getAction()="+event.getAction()+"isNext="+isNext);
						if (isNext) {
							if (sliderView.getVisibility()!=View.VISIBLE) {
								sliderView.setVisibility(View.VISIBLE);
								Animation animation=AnimationUtils.loadAnimation(getActivity(),R.anim.scale_in_right);
								sliderView.startAnimation(animation);
								
							}else{
								changeFragment();
							}
							isNext = false;
						}
						break;
					}
					return true;
				}
			});
		}
	}

	private void customClock(){
		timing = 0;
		if(null == mHandler && null == runnable){
			mHandler = new Handler();
			runnable = new Runnable() {
				@Override
				public void run() {
					long tempTime = customTime;
					tempTime = tempTime - (timing++);
					if(tempTime < 0){
						timing = 0;
						loadData();
					}else{
						dealTime(tempTime);
					}
					long now = SystemClock.uptimeMillis();
					long next = now + (1000 - now % 1000);
					mHandler.postAtTime(runnable, next);
				}
			};
			runnable.run();
		}
	}

	private void dealTime(long time) {
		long hours = time / (60 * 60);
		long minutes = ((time % (24 * 60 * 60)) % (60 * 60)) / 60;
		long second = ((time % (24 * 60 * 60)) % (60 * 60)) % 60;
		String hoursStr = timeStrFormat(String.valueOf(hours));
		String minutesStr = timeStrFormat(String.valueOf(minutes));
		String secondStr = timeStrFormat(String.valueOf(second));
		tvSecondKill.setText(String.format("（还剩  %s:%s:%s 结束）",hoursStr,minutesStr,secondStr));
	}

	private static String timeStrFormat(String timeStr) {
		switch (timeStr.length()) {
		case 1:
			timeStr = "0" + timeStr;
			break;
		}
		return timeStr;
	}
	/**
	 * 
	 * @author LK
	 * @methods isOK 
	 * @description 描述信息 验证是否是日期格式
	 * @date 2015-1-21 上午11:09:13
	 * @param str
	 * @return 参数说明
	 */
	public boolean isOK(String str) {
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
		try {
			format.parse(str);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		//注销广播接受器
		getActivity().unregisterReceiver(receiveBroadCast);
	}
}
